#include ".\configviewmanager.h"
#include <QVBoxLayout>
#include <QScrollArea>
#include <QGroupBox>
#include <QGridLayout>
#include <QLabel>
#include <QTreeWidget>
#include <QTextEdit>
#include <QFrame>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>
#include <QSpacerItem>
#include <QLineEdit>
#include <QComboBox>
#include <QCheckBox>
#include <QPushButton>
#include <QMessageBox>
#include <QButtonGroup>
#include <QRadioButton>
#include <QSpinBox>
#include <QDoubleSpinBox>
#include <QJsonArray>

ConfigViewManager::ConfigViewManager(QStackedWidget *stackedWidget, QObject *parent)
    : QObject(parent), m_stackedWidget(stackedWidget)
{
    // 初始化所有视图
    initGroupView();
    initPropertyView();
    initJsonView();
    initCardView();

    // 默认显示分组视图
    setCurrentView(GroupView);
}

void ConfigViewManager::setCurrentView(ConfigViewType type)
{
    if (!m_stackedWidget) return;

    switch (type) {
    case GroupView:
        m_stackedWidget->setCurrentWidget(m_groupView);
        updateGroupView();
        break;
    case PropertyView:
        m_stackedWidget->setCurrentWidget(m_propertyView);
        updatePropertyView();
        break;
    case JsonView:
        m_stackedWidget->setCurrentWidget(m_jsonView);
        updateJsonView();
        break;
    case CardView:
        m_stackedWidget->setCurrentWidget(m_cardView);
        updateCardView();
        break;
    }
}

void ConfigViewManager::updateConfig(const QJsonArray &configArray)
{
    m_originalConfig = configArray;
    m_currentConfig = configArray;
    m_configArray = configArray;
    m_rawJson = QJsonDocument(configArray).toJson(QJsonDocument::Indented);

    // 更新当前视图
    if (m_stackedWidget->currentWidget() == m_groupView) {
        updateGroupView();
    } else if (m_stackedWidget->currentWidget() == m_propertyView) {
        updatePropertyView();
    } else if (m_stackedWidget->currentWidget() == m_jsonView) {
        updateJsonView();
    } else if (m_stackedWidget->currentWidget() == m_cardView) {
        updateCardView();
    }

    emit configModified();
}

QJsonArray ConfigViewManager::getModifiedConfig() const
{
    return m_currentConfig;
}

void ConfigViewManager::resetToOriginal()
{
    m_currentConfig = m_originalConfig;
    updateConfig(m_currentConfig);
}

void ConfigViewManager::applyEdits()
{
    // 遍历所有编辑控件，更新配置
    for (auto it = m_editWidgets.begin(); it != m_editWidgets.end(); ++it) {
        QWidget *widget = it.key();
        int configIndex = it.value().first;
        int itemIndex = it.value().second.first;
        QString key = it.value().second.second;

        if (configIndex < 0 || configIndex >= m_currentConfig.size()) continue;

        QJsonObject configObj = m_currentConfig[configIndex].toObject();
        if (configObj.contains("config")) {
            QJsonValue configValue = configObj["config"];

            if (itemIndex >= 0) {
                // 数组项中的值
                if (configValue.isArray()) {
                    QJsonArray configArray = configValue.toArray();
                    if (itemIndex < configArray.size()) {
                        QJsonObject itemObj = configArray[itemIndex].toObject();
                        itemObj[key] = getValueFromWidget(widget);
                        configArray[itemIndex] = itemObj;
                        configObj["config"] = configArray;
                    }
                }
            } else {
                // 直接配置值
                if (configValue.isObject()) {
                    QJsonObject configObjValue = configValue.toObject();
                    configObjValue[key] = getValueFromWidget(widget);
                    configObj["config"] = configObjValue;
                } else if (configValue.isArray()) {
                    // 处理ADC通道顺序
                    QJsonArray configArray = configValue.toArray();
                    configObj["config"] = configArray;
                }
            }

            m_currentConfig[configIndex] = configObj;
        }
    }

    // 更新视图显示修改后的配置
    updateConfig(m_currentConfig);
}

void ConfigViewManager::sendCurrentConfig()
{
    // 应用所有编辑
    applyEdits();

    // 发出发送请求信号
    emit sendConfigRequested(m_currentConfig);
}

void ConfigViewManager::initGroupView()
{
    m_groupView = new QWidget();
    QVBoxLayout *mainLayout = new QVBoxLayout(m_groupView);
    mainLayout->setContentsMargins(0, 0, 0, 0);

    // 创建滚动区域
    QScrollArea *scrollArea = new QScrollArea();
    scrollArea->setWidgetResizable(true);
    scrollArea->setFrameShape(QFrame::NoFrame);

    QWidget *scrollContent = new QWidget();
    QVBoxLayout *contentLayout = new QVBoxLayout(scrollContent);
    contentLayout->setAlignment(Qt::AlignTop);

    scrollArea->setWidget(scrollContent);
    mainLayout->addWidget(scrollArea);

    m_stackedWidget->addWidget(m_groupView);
}

void ConfigViewManager::initPropertyView()
{
    m_propertyView = new QWidget();
    QVBoxLayout *mainLayout = new QVBoxLayout(m_propertyView);
    mainLayout->setContentsMargins(0, 0, 0, 0);

    // 创建树形视图
    QTreeWidget *treeWidget = new QTreeWidget();
    treeWidget->setHeaderLabels({"配置项", "值"});
    treeWidget->setColumnWidth(0, 250);
    treeWidget->setStyleSheet(
        "QTreeWidget {"
        "   background-color: #ffffff;"
        "   border: none;"
        "}"
        "QTreeWidget::item {"
        "   padding: 5px;"
        "}"
    );

    mainLayout->addWidget(treeWidget);
    m_stackedWidget->addWidget(m_propertyView);
}

void ConfigViewManager::initJsonView()
{
    m_jsonView = new QWidget();
    QVBoxLayout *mainLayout = new QVBoxLayout(m_jsonView);
    mainLayout->setContentsMargins(0, 0, 0, 0);

    // 创建文本编辑框
    QTextEdit *jsonEdit = new QTextEdit();
    jsonEdit->setReadOnly(false); // 允许编辑
    jsonEdit->setFont(QFont("Consolas", 10));
    jsonEdit->setStyleSheet(
        "QTextEdit {"
        "   background-color: #ffffff;"
        "   border: 1px solid #d0d0d0;"
        "   border-radius: 3px;"
        "   padding: 5px;"
        "}"
    );

    mainLayout->addWidget(jsonEdit);
    m_stackedWidget->addWidget(m_jsonView);
}

void ConfigViewManager::initCardView()
{
    m_cardView = new QWidget();
    QVBoxLayout *mainLayout = new QVBoxLayout(m_cardView);
    mainLayout->setContentsMargins(0, 0, 0, 0);

    // 创建滚动区域
    QScrollArea *scrollArea = new QScrollArea();
    scrollArea->setWidgetResizable(true);
    scrollArea->setFrameShape(QFrame::NoFrame);

    QWidget *scrollContent = new QWidget();
    QVBoxLayout *contentLayout = new QVBoxLayout(scrollContent);
    contentLayout->setAlignment(Qt::AlignTop);

    scrollArea->setWidget(scrollContent);
    mainLayout->addWidget(scrollArea);

    m_stackedWidget->addWidget(m_cardView);
}
void ConfigViewManager::updateGroupView()
{
    if (!m_groupView) return;

    // 获取滚动区域内容
    QScrollArea *scrollArea = m_groupView->findChild<QScrollArea*>();
    if (!scrollArea) return;

    QWidget *scrollContent = scrollArea->widget();
    if (!scrollContent) return;

    // 清除旧内容
    QLayout *contentLayout = scrollContent->layout();
    if (contentLayout) {
        QLayoutItem *child;
        while ((child = contentLayout->takeAt(0)) != nullptr) {
            delete child->widget();
            delete child;
        }
    } else {
        contentLayout = new QVBoxLayout(scrollContent);
        contentLayout->setAlignment(Qt::AlignTop);
    }

    // 清除编辑控件映射
    m_editWidgets.clear();

    // 检查下载模式配置
    int sop2Index = -1;
    int bootIndex = -1;
    bool hasSOP2 = false;
    bool hasBOOT = false;

    for (int i = 0; i < m_currentConfig.size(); i++) {
        QJsonObject obj = m_currentConfig[i].toObject();
        if (obj["type"].toString() == "down_sop2") {
            sop2Index = i;
            hasSOP2 = true;
        } else if (obj["type"].toString() == "down_boot") {
            bootIndex = i;
            hasBOOT = true;
        }
    }

    // 创建下载模式选择器
    if (hasSOP2 || hasBOOT) {
        QGroupBox *modeGroup = new QGroupBox("下载模式配置");
        modeGroup->setStyleSheet(
            "QGroupBox {"
            "   border: 1px solid #aaa;"
            "   border-radius: 5px;"
            "   margin-top: 10px;"
            "   font-weight: bold;"
            "}"
            "QGroupBox::title {"
            "   subcontrol-origin: margin;"
            "   padding: 0 5px;"
            "   background-color: #e9e9e9;"
            "}"
        );

        QHBoxLayout *modeLayout = new QHBoxLayout(modeGroup);

        QButtonGroup *buttonGroup = new QButtonGroup(this);
        QRadioButton *sop2Radio = new QRadioButton("SOP2模式");
        QRadioButton *bootRadio = new QRadioButton("BOOT模式");

        buttonGroup->addButton(sop2Radio);
        buttonGroup->addButton(bootRadio);
        modeLayout->addWidget(sop2Radio);
        modeLayout->addWidget(bootRadio);

        if (hasSOP2) sop2Radio->setChecked(true);
        if (hasBOOT) bootRadio->setChecked(true);

        // 处理模式切换
        connect(buttonGroup, QOverload<QAbstractButton*>::of(&QButtonGroup::buttonClicked),
                [this, hasSOP2, hasBOOT, sop2Index, bootIndex](QAbstractButton *button) {
            if (button->text() == "SOP2模式") {
                // 删除当前配置
                m_currentConfig.removeAt(sop2Index);
                // 添加SOP2配置
                QJsonObject sop2Config;
                sop2Config["type"] = "down_sop2";
                QJsonObject config;
                config["device"] = "default";
                config["output_pin"] = 0;
                sop2Config["config"] = config;
                m_currentConfig.append(sop2Config);

                // 删除BOOT配置
                if (hasBOOT) {
                    m_currentConfig.removeAt(bootIndex);
                }

                updateGroupView();
            }
            else if (button->text() == "BOOT模式") {
                //删除当前配置
                m_currentConfig.removeAt(bootIndex);
                // 添加BOOT配置
                QJsonObject bootConfig;
                bootConfig["type"] = "down_boot";
                QJsonObject config;
                config["device"] = "default";
                config["output_pin"] = 0;
                config["control"] = QJsonArray();
                bootConfig["config"] = config;
                m_currentConfig.append(bootConfig);

                // 删除SOP2配置
                if (hasSOP2) {
                    m_currentConfig.removeAt(sop2Index);
                }

                updateGroupView();
            }
        });

        contentLayout->addWidget(modeGroup);
    }

    // 动态构建分组视图
    for (int configIndex = 0; configIndex < m_currentConfig.size(); configIndex++) {
        QJsonValue configVal = m_currentConfig[configIndex];
        QJsonObject configObj = configVal.toObject();
        QString type = configObj["type"].toString();

        // 创建分组框
        QGroupBox *groupBox = new QGroupBox(type.toUpper() + " 配置");
        groupBox->setStyleSheet(
            "QGroupBox {"
            "   border: 1px solid #aaa;"
            "   border-radius: 5px;"
            "   margin-top: 10px;"
            "   font-weight: bold;"
            "}"
            "QGroupBox::title {"
            "   subcontrol-origin: margin;"
            "   padding: 0 5px;"
            "   background-color: #e9e9e9;"
            "}"
        );

        QGridLayout *gridLayout = new QGridLayout(groupBox);
        gridLayout->setColumnStretch(1, 1); // 第二列拉伸

        int row = 0;

        // 处理不同类型的配置
        if (configObj.contains("config")) {
            QJsonValue configValue = configObj["config"];

            if (type == "io") {
                QJsonArray ioArray = configValue.toArray();
                for (int itemIndex = 0; itemIndex < ioArray.size(); itemIndex++) {
                    QJsonValue ioVal = ioArray[itemIndex];
                    QJsonObject ioObj = ioVal.toObject();

                    gridLayout->addWidget(new QLabel("引脚:"), row, 0);
                    // 引脚号可编辑
                    QWidget *pinWidget = createEditableWidget("io_pin", ioObj["io_pin"], configIndex, itemIndex);
                    gridLayout->addWidget(pinWidget, row, 1);

                    gridLayout->addWidget(new QLabel("模式:"), row, 2);
                    QWidget *modeWidget = createEditableWidget("mode", ioObj["mode"], configIndex, itemIndex);
                    gridLayout->addWidget(modeWidget, row, 3);

                    // 当模式为输出、输入或PWM时显示激活状态
                    QString mode = ioObj["mode"].toString();
                    if (mode == "output" || mode == "input" || mode == "pwm") {
                        gridLayout->addWidget(new QLabel("激活状态:"), row, 4);
                        QWidget *stateWidget = createEditableWidget("active_state", ioObj["active_state"], configIndex, itemIndex);
                        gridLayout->addWidget(stateWidget, row, 5);
                    }

                    // 删除按钮
                    QPushButton *deleteButton = new QPushButton("删除");
                    deleteButton->setStyleSheet(
                        "QPushButton {"
                        "   background-color: #e74c3c;"
                        "   color: white;"
                        "   padding: 4px 8px;"
                        "   border-radius: 4px;"
                        "}"
                        "QPushButton:hover { background-color: #c0392b; }"
                    );
                    connect(deleteButton, &QPushButton::clicked, this, [this, configIndex, itemIndex, ioArray]() mutable {
                        ioArray.removeAt(itemIndex);

                        QJsonObject configObj = m_currentConfig[configIndex].toObject();
                        configObj["config"] = ioArray;
                        m_currentConfig[configIndex] = configObj;

                        updateGroupView();
                    });
                    gridLayout->addWidget(deleteButton, row, 6);

                    row++;
                }

                // 添加引脚按钮
                QPushButton *addPinButton = new QPushButton("添加引脚");
                addPinButton->setStyleSheet(
                    "QPushButton {"
                    "   background-color: #3498db;"
                    "   color: white;"
                    "   padding: 6px 12px;"
                    "   border-radius: 4px;"
                    "}"
                    "QPushButton:hover { background-color: #2980b9; }"
                );
                connect(addPinButton, &QPushButton::clicked, this, [this, configIndex, ioArray]() mutable {
                    QJsonObject newPin;
                    newPin["io_pin"] = 0;
                    newPin["mode"] = "input";
                    newPin["active_state"] = false;

                    ioArray.append(newPin);

                    QJsonObject configObj = m_currentConfig[configIndex].toObject();
                    configObj["config"] = ioArray;
                    m_currentConfig[configIndex] = configObj;

                    updateGroupView();
                });
                gridLayout->addWidget(addPinButton, row, 0, 1, 7);
                row++;
            }
            else if (type == "adc") {
                QJsonObject adcObj = configValue.toObject();
                QJsonArray channels = adcObj["channels"].toArray();

                gridLayout->addWidget(new QLabel("通道数量:"), row, 0);
                gridLayout->addWidget(new QLabel(QString::number(channels.size())), row, 1);
                row++;

                gridLayout->addWidget(new QLabel("通道列表:"), row, 0);

                // 通道顺序编辑
                for (int i = 0; i < channels.size(); i++) {
                    QHBoxLayout *channelLayout = new QHBoxLayout();

                    // 通道显示
                    QLineEdit *channelEdit = new QLineEdit(channels[i].toString());
                    channelLayout->addWidget(channelEdit);

                    // 上移按钮
                    if (i > 0) {
                        QPushButton *upButton = new QPushButton("↑");
                        upButton->setFixedWidth(30);
                        connect(upButton, &QPushButton::clicked, this, [this, configIndex, i]() mutable {
                            // 从当前配置中获取channels数组
                            if (configIndex >= m_currentConfig.size()) return;
                            QJsonObject configObj = m_currentConfig[configIndex].toObject();
                            if (!configObj.contains("config")) return;
                            QJsonValue configValue = configObj["config"];
                            if (!configValue.isObject()) return;
                            QJsonObject adcObj = configValue.toObject();
                            QJsonArray channels = adcObj["channels"].toArray();
                            if (i >= channels.size()) return;

                            // 交换位置
                            QJsonValue temp = channels[i];
                            channels[i] = channels[i-1];
                            channels[i-1] = temp;

                            // 更新配置
                            adcObj["channels"] = channels;
                            configObj["config"] = adcObj;
                            m_currentConfig[configIndex] = configObj;

                            // 刷新视图
                            updateGroupView();
                        });
                        channelLayout->addWidget(upButton);
                    }

                    // 下移按钮
                    if (i < channels.size()-1) {
                        QPushButton *downButton = new QPushButton("↓");
                        downButton->setFixedWidth(30);
                        connect(downButton, &QPushButton::clicked, this, [this, configIndex, i]() mutable {
                            // 从当前配置中获取channels数组
                            if (configIndex >= m_currentConfig.size()) return;
                            QJsonObject configObj = m_currentConfig[configIndex].toObject();
                            if (!configObj.contains("config")) return;
                            QJsonValue configValue = configObj["config"];
                            if (!configValue.isObject()) return;
                            QJsonObject adcObj = configValue.toObject();
                            QJsonArray channels = adcObj["channels"].toArray();
                            if (i >= channels.size()) return;

                            // 交换位置
                            QJsonValue temp = channels[i];
                            channels[i] = channels[i+1];
                            channels[i+1] = temp;

                            // 更新配置
                            adcObj["channels"] = channels;
                            configObj["config"] = adcObj;
                            m_currentConfig[configIndex] = configObj;

                            // 刷新视图
                            updateGroupView();
                        });
                        channelLayout->addWidget(downButton);
                    }

                    // 连接通道名称编辑的信号
                    connect(channelEdit, &QLineEdit::textChanged, this, [this, configIndex, i, channelEdit]() {
                        // 从当前配置中获取channels数组
                        if (configIndex >= m_currentConfig.size()) return;
                        QJsonObject configObj = m_currentConfig[configIndex].toObject();
                        if (!configObj.contains("config")) return;
                        QJsonValue configValue = configObj["config"];
                        if (!configValue.isObject()) return;
                        QJsonObject adcObj = configValue.toObject();
                        QJsonArray channels = adcObj["channels"].toArray();
                        if (i >= channels.size()) return;

                        // 更新通道名称
                        channels[i] = channelEdit->text();

                        // 更新配置
                        adcObj["channels"] = channels;
                        configObj["config"] = adcObj;
                        m_currentConfig[configIndex] = configObj;
                    });

                    gridLayout->addLayout(channelLayout, row, 1, 1, 6);
                    row++;
                }

                // 添加通道按钮
                QPushButton *addChannelButton = new QPushButton("添加通道");
                addChannelButton->setStyleSheet(
                    "QPushButton {"
                    "   background-color: #3498db;"
                    "   color: white;"
                    "   padding: 6px 12px;"
                    "   border-radius: 4px;"
                    "}"
                    "QPushButton:hover { background-color: #2980b9; }"
                );
                connect(addChannelButton, &QPushButton::clicked, this, [this, configIndex, channels]() mutable {
                    channels.append("新通道");

                    QJsonObject configObj = m_currentConfig[configIndex].toObject();
                    QJsonObject adcObj = configObj["config"].toObject();
                    adcObj["channels"] = channels;
                    configObj["config"] = adcObj;
                    m_currentConfig[configIndex] = configObj;

                    updateGroupView();
                });
                gridLayout->addWidget(addChannelButton, row, 0, 1, 7);
                row++;
            }
            else if (type == "down_sop2") {
                QJsonObject sopObj = configValue.toObject();

                gridLayout->addWidget(new QLabel("设备:"), row, 0);
                QWidget *deviceWidget = createEditableWidget("device", sopObj["device"], configIndex);
                gridLayout->addWidget(deviceWidget, row, 1);

                gridLayout->addWidget(new QLabel("输出引脚:"), row, 2);
                QWidget *pinWidget = createEditableWidget("output_pin", sopObj["output_pin"], configIndex);
                gridLayout->addWidget(pinWidget, row, 3);
                row++;
            }
            else if (type == "down_boot") {
                QJsonObject bootObj = configValue.toObject();

                gridLayout->addWidget(new QLabel("设备:"), row, 0);
                QWidget *deviceWidget = createEditableWidget("device", bootObj["device"], configIndex);
                gridLayout->addWidget(deviceWidget, row, 1);

                gridLayout->addWidget(new QLabel("输出引脚:"), row, 2);
                QWidget *pinWidget = createEditableWidget("output_pin", bootObj["output_pin"], configIndex);
                gridLayout->addWidget(pinWidget, row, 3);
                row++;

                // 控制引脚配置
                QLabel *ctrlTitle = new QLabel("控制引脚配置:");
                ctrlTitle->setStyleSheet("font-weight: bold;");
                gridLayout->addWidget(ctrlTitle, row, 0, 1, 2);
                row++;

                QJsonArray controlArray = bootObj["control"].toArray();
                for (int itemIndex = 0; itemIndex < controlArray.size(); itemIndex++) {
                    QJsonValue ctrlVal = controlArray[itemIndex];
                    QJsonObject ctrlObj = ctrlVal.toObject();

                    gridLayout->addWidget(new QLabel("引脚:"), row, 1);
                    QWidget *pinWidget = createEditableWidget("io_pin", ctrlObj["io_pin"], configIndex, itemIndex);
                    gridLayout->addWidget(pinWidget, row, 2);

                    gridLayout->addWidget(new QLabel("状态:"), row, 3);
                    QWidget *stateWidget = createEditableWidget("active_state", ctrlObj["active_state"], configIndex, itemIndex);
                    gridLayout->addWidget(stateWidget, row, 4);

                    // 删除按钮
                    QPushButton *deleteButton = new QPushButton("删除");
                    deleteButton->setStyleSheet(
                        "QPushButton {"
                        "   background-color: #e74c3c;"
                        "   color: white;"
                        "   padding: 4px 8px;"
                        "   border-radius: 4px;"
                        "}"
                        "QPushButton:hover { background-color: #c0392b; }"
                    );
                    connect(deleteButton, &QPushButton::clicked, this, [this, configIndex, itemIndex, controlArray]() mutable {
                        controlArray.removeAt(itemIndex);

                        QJsonObject bootObj = m_currentConfig[configIndex].toObject();
                        QJsonObject config = bootObj["config"].toObject();
                        config["control"] = controlArray;
                        bootObj["config"] = config;
                        m_currentConfig[configIndex] = bootObj;

                        updateGroupView();
                    });
                    gridLayout->addWidget(deleteButton, row, 5);

                    row++;
                }

                // 添加控制引脚按钮
                QPushButton *addCtrlButton = new QPushButton("添加控制引脚");
                addCtrlButton->setStyleSheet(
                    "QPushButton {"
                    "   background-color: #3498db;"
                    "   color: white;"
                    "   padding: 6px 12px;"
                    "   border-radius: 4px;"
                    "}"
                    "QPushButton:hover { background-color: #2980b9; }"
                );
                connect(addCtrlButton, &QPushButton::clicked, this, [this, configIndex, controlArray]() mutable {
                    QJsonObject newCtrl;
                    newCtrl["io_pin"] = 0;
                    newCtrl["active_state"] = false;

                    controlArray.append(newCtrl);

                    QJsonObject bootObj = m_currentConfig[configIndex].toObject();
                    QJsonObject config = bootObj["config"].toObject();
                    config["control"] = controlArray;
                    bootObj["config"] = config;
                    m_currentConfig[configIndex] = bootObj;

                    updateGroupView();
                });
                gridLayout->addWidget(addCtrlButton, row, 0, 1, 7);
                row++;
            }
        }

        contentLayout->addWidget(groupBox);
    }

    // 添加操作按钮
    QWidget *buttonContainer = new QWidget();
    QHBoxLayout *buttonLayout = new QHBoxLayout(buttonContainer);
    buttonLayout->setContentsMargins(10, 10, 10, 10);

    QPushButton *applyButton = new QPushButton("应用修改");
    applyButton->setStyleSheet(
        "QPushButton {"
        "   background-color: #4CAF50;"
        "   color: white;"
        "   padding: 8px 16px;"
        "   border-radius: 4px;"
        "}"
        "QPushButton:hover { background-color: #45a049; }"
    );
    connect(applyButton, &QPushButton::clicked, this, &ConfigViewManager::applyEdits);

    QPushButton *resetButton = new QPushButton("重置修改");
    resetButton->setStyleSheet(
        "QPushButton {"
        "   background-color: #f0ad4e;"
        "   color: white;"
        "   padding: 8px 16px;"
        "   border-radius: 4px;"
        "}"
        "QPushButton:hover { background-color: #ec971f; }"
    );
    connect(resetButton, &QPushButton::clicked, this, &ConfigViewManager::resetToOriginal);

    QPushButton *sendButton = new QPushButton("发送配置");
    sendButton->setStyleSheet(
        "QPushButton {"
        "   background-color: #5bc0de;"
        "   color: white;"
        "   padding: 8px 16px;"
        "   border-radius: 4px;"
        "}"
        "QPushButton:hover { background-color: #46b8da; }"
    );
    connect(sendButton, &QPushButton::clicked, this, &ConfigViewManager::sendCurrentConfig);

    buttonLayout->addStretch();
    buttonLayout->addWidget(applyButton);
    buttonLayout->addWidget(resetButton);
    buttonLayout->addWidget(sendButton);

    contentLayout->addWidget(buttonContainer);
    contentLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding));
}

void ConfigViewManager::updatePropertyView()
{
    if (!m_propertyView) return;

    QTreeWidget *treeWidget = m_propertyView->findChild<QTreeWidget*>();
    if (!treeWidget) return;

    // 清除旧内容
    treeWidget->clear();

    // 设置表头
    treeWidget->setHeaderLabels({"配置项", "值"});

    // 构建树形结构
    for (const QJsonValue &configVal : m_configArray) {
        QJsonObject configObj = configVal.toObject();
        QString type = configObj["type"].toString();

        QTreeWidgetItem *typeItem = new QTreeWidgetItem(treeWidget, {type});
        typeItem->setExpanded(true);

        if (configObj.contains("config")) {
            QJsonValue configValue = configObj["config"];

            if (type == "io") {
                QJsonArray ioArray = configValue.toArray();
                for (const QJsonValue &ioVal : ioArray) {
                    QJsonObject ioObj = ioVal.toObject();
                    QString pin = "引脚 " + QString::number(ioObj["io_pin"].toInt());

                    QTreeWidgetItem *pinItem = new QTreeWidgetItem(typeItem, {pin});
                    pinItem->addChild(new QTreeWidgetItem({"模式", ioObj["mode"].toString()}));

                    if (ioObj.contains("active_state")) {
                        pinItem->addChild(new QTreeWidgetItem({
                            "激活状态",
                            ioObj["active_state"].toBool() ? "高电平" : "低电平"
                        }));
                    }
                }
            } else if (type == "adc") {
                QJsonObject adcObj = configValue.toObject();
                QJsonArray channels = adcObj["channels"].toArray();

                QStringList channelList;
                for (const QJsonValue &ch : channels) {
                    channelList << ch.toString();
                }

                typeItem->addChild(new QTreeWidgetItem({
                    "通道列表",
                    channelList.join(", ")
                }));
            } else if (type == "down_sop2") {
                QJsonObject sopObj = configValue.toObject();

                typeItem->addChild(new QTreeWidgetItem({"设备", sopObj["device"].toString()}));
                typeItem->addChild(new QTreeWidgetItem({"输出引脚", sopObj["output_pin"].toString()}));
            } else if (type == "down_boot") {
                QJsonObject bootObj = configValue.toObject();

                typeItem->addChild(new QTreeWidgetItem({"设备", bootObj["device"].toString()}));
                typeItem->addChild(new QTreeWidgetItem({"输出引脚", bootObj["output_pin"].toString()}));

                // 控制引脚
                QTreeWidgetItem *ctrlItem = new QTreeWidgetItem(typeItem, {"控制引脚"});
                for (const QJsonValue &ctrlVal : bootObj["control"].toArray()) {
                    QJsonObject ctrlObj = ctrlVal.toObject();
                    QString pin = "引脚 " + QString::number(ctrlObj["io_pin"].toInt());

                    QTreeWidgetItem *pinItem = new QTreeWidgetItem(ctrlItem, {pin});
                    pinItem->addChild(new QTreeWidgetItem({
                        "状态",
                        ctrlObj["active_state"].toBool() ? "高电平" : "低电平"
                    }));
                }
            } else {
                // 通用配置处理
                if (configValue.isObject()) {
                    QJsonObject obj = configValue.toObject();
                    for (auto it = obj.begin(); it != obj.end(); ++it) {
                        typeItem->addChild(new QTreeWidgetItem({
                            it.key(),
                            it.value().toVariant().toString()
                        }));
                    }
                } else if (configValue.isArray()) {
                    QJsonArray arr = configValue.toArray();
                    for (int i = 0; i < arr.size(); ++i) {
                        QTreeWidgetItem *item = new QTreeWidgetItem(typeItem, {
                            QString("项目 %1").arg(i+1)
                        });

                        if (arr[i].isObject()) {
                            QJsonObject obj = arr[i].toObject();
                            for (auto it = obj.begin(); it != obj.end(); ++it) {
                                item->addChild(new QTreeWidgetItem({
                                    it.key(),
                                    it.value().toVariant().toString()
                                }));
                            }
                        } else {
                            item->addChild(new QTreeWidgetItem({
                                "值",
                                arr[i].toVariant().toString()
                            }));
                        }
                    }
                }
            }
        }
    }

    treeWidget->expandAll();
}

void ConfigViewManager::updateJsonView()
{
    if (!m_jsonView) return;

    QTextEdit *jsonEdit = m_jsonView->findChild<QTextEdit*>();
    if (!jsonEdit) return;

    // 显示原始JSON数据
    jsonEdit->setText(m_rawJson);
}

void ConfigViewManager::updateCardView()
{
    if (!m_cardView) return;

    // 获取滚动区域内容
    QScrollArea *scrollArea = m_cardView->findChild<QScrollArea*>();
    if (!scrollArea) return;

    QWidget *scrollContent = scrollArea->widget();
    if (!scrollContent) return;

    // 清除旧内容
    QLayout *contentLayout = scrollContent->layout();
    if (contentLayout) {
        QLayoutItem *child;
        while ((child = contentLayout->takeAt(0)) != nullptr) {
            delete child->widget();
            delete child;
        }
    } else {
        contentLayout = new QVBoxLayout(scrollContent);
        contentLayout->setAlignment(Qt::AlignTop);
    }

    // 创建卡片视图
    for (const QJsonValue &configVal : m_configArray) {
        QJsonObject configObj = configVal.toObject();
        QString type = configObj["type"].toString();
        QString title = type.toUpper() + " 配置";

        // 创建卡片容器
        QFrame *card = new QFrame();
        card->setFrameShape(QFrame::StyledPanel);
        card->setStyleSheet(
            "QFrame {"
            "   background-color: white;"
            "   border-radius: 8px;"
            "   padding: 15px;"
            "   margin: 10px;"
            "   box-shadow: 0 2px 5px rgba(0,0,0,0.1);"
            "}"
        );

        QVBoxLayout *cardLayout = new QVBoxLayout(card);

        // 卡片标题
        QLabel *titleLabel = new QLabel(title);
        titleLabel->setStyleSheet(
            "QLabel {"
            "   font-weight: bold;"
            "   font-size: 14pt;"
            "   color: #2c3e50;"
            "   padding-bottom: 10px;"
            "   border-bottom: 1px solid #ecf0f1;"
            "}"
        );
        cardLayout->addWidget(titleLabel);

        // 卡片内容
        QWidget *contentWidget = new QWidget();
        QGridLayout *gridLayout = new QGridLayout(contentWidget);
        gridLayout->setColumnStretch(1, 1); // 第二列拉伸

        int row = 0;

        if (configObj.contains("config")) {
            QJsonValue configValue = configObj["config"];

            if (type == "io") {
                QJsonArray ioArray = configValue.toArray();
                for (const QJsonValue &ioVal : ioArray) {
                    QJsonObject ioObj = ioVal.toObject();

                    gridLayout->addWidget(new QLabel("<b>引脚:</b>"), row, 0);
                    gridLayout->addWidget(new QLabel(QString::number(ioObj["io_pin"].toInt())), row, 1);

                    gridLayout->addWidget(new QLabel("<b>模式:</b>"), row, 2);
                    gridLayout->addWidget(new QLabel(ioObj["mode"].toString()), row, 3);

                    if (ioObj.contains("active_state")) {
                        gridLayout->addWidget(new QLabel("<b>激活状态:</b>"), row, 4);

                        QLabel *stateLabel = new QLabel(ioObj["active_state"].toBool() ? "高电平" : "低电平");
                        stateLabel->setStyleSheet(ioObj["active_state"].toBool() ?
                            "color: #27ae60;" : "color: #e74c3c;");
                        gridLayout->addWidget(stateLabel, row, 5);
                    }

                    row++;
                }
            } else if (type == "adc") {
                QJsonObject adcObj = configValue.toObject();
                QJsonArray channels = adcObj["channels"].toArray();

                gridLayout->addWidget(new QLabel("<b>通道数量:</b>"), row, 0);
                gridLayout->addWidget(new QLabel(QString::number(channels.size())), row, 1);
                row++;

                gridLayout->addWidget(new QLabel("<b>通道列表:</b>"), row, 0);

                QStringList channelList;
                for (const QJsonValue &ch : channels) {
                    channelList << ch.toString();
                }

                QLabel *channelsLabel = new QLabel(channelList.join(", "));
                channelsLabel->setWordWrap(true);
                gridLayout->addWidget(channelsLabel, row, 1, 1, 5);
                row++;
            } else if (type == "down_sop2") {
                QJsonObject sopObj = configValue.toObject();

                gridLayout->addWidget(new QLabel("<b>设备:</b>"), row, 0);
                gridLayout->addWidget(new QLabel(sopObj["device"].toString()), row, 1);
                row++;

                gridLayout->addWidget(new QLabel("<b>输出引脚:</b>"), row, 0);
                gridLayout->addWidget(new QLabel(sopObj["output_pin"].toString()), row, 1);
                row++;
            } else if (type == "down_boot") {
                QJsonObject bootObj = configValue.toObject();

                gridLayout->addWidget(new QLabel("<b>设备:</b>"), row, 0);
                gridLayout->addWidget(new QLabel(bootObj["device"].toString()), row, 1);
                row++;

                gridLayout->addWidget(new QLabel("<b>输出引脚:</b>"), row, 0);
                gridLayout->addWidget(new QLabel(bootObj["output_pin"].toString()), row, 1);
                row++;

                // 控制引脚
                QLabel *ctrlTitle = new QLabel("<b>控制引脚配置:</b>");
                ctrlTitle->setStyleSheet("color: #2c3e50;");
                gridLayout->addWidget(ctrlTitle, row, 0, 1, 6);
                row++;

                for (const QJsonValue &ctrlVal : bootObj["control"].toArray()) {
                    QJsonObject ctrlObj = ctrlVal.toObject();

                    gridLayout->addWidget(new QLabel("引脚:"), row, 1);
                    gridLayout->addWidget(new QLabel(QString::number(ctrlObj["io_pin"].toInt())), row, 2);

                    gridLayout->addWidget(new QLabel("状态:"), row, 3);

                    QLabel *stateLabel = new QLabel(ctrlObj["active_state"].toBool() ? "高电平" : "低电平");
                    stateLabel->setStyleSheet(ctrlObj["active_state"].toBool() ?
                        "color: #27ae60;" : "color: #e74c3c;");
                    gridLayout->addWidget(stateLabel, row, 4);

                    row++;
                }
            } else {
                // 通用配置处理
                if (configValue.isObject()) {
                    QJsonObject obj = configValue.toObject();
                    for (auto it = obj.begin(); it != obj.end(); ++it) {
                        gridLayout->addWidget(new QLabel("<b>" + it.key() + ":</b>"), row, 0);
                        gridLayout->addWidget(new QLabel(it.value().toVariant().toString()), row, 1);
                        row++;
                    }
                } else if (configValue.isArray()) {
                    QJsonArray arr = configValue.toArray();
                    for (int i = 0; i < arr.size(); ++i) {
                        gridLayout->addWidget(new QLabel("<b>项目 " + QString::number(i+1) + ":</b>"), row, 0);
                        gridLayout->addWidget(new QLabel(arr[i].toVariant().toString()), row, 1);
                        row++;
                    }
                }
            }
        }

        cardLayout->addWidget(contentWidget);
        contentLayout->addWidget(card);
    }

    // 添加伸缩项
    contentLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding));
}

QWidget* ConfigViewManager::createEditableWidget(const QString &key, const QJsonValue &value,
                                                int configIndex, int itemIndex)
{
    QWidget *container = new QWidget();
    QHBoxLayout *layout = new QHBoxLayout(container);
    layout->setContentsMargins(0, 0, 0, 0);

    if (value.isBool()) {
        QCheckBox *checkBox = new QCheckBox();
        checkBox->setChecked(value.toBool());
        layout->addWidget(checkBox);
        m_editWidgets[checkBox] = qMakePair(configIndex, qMakePair(itemIndex, key));
    }
    else if (value.isDouble() || value.isString()) {
        // 引脚号使用QSpinBox
        if (key == "io_pin" || key == "output_pin") {
            QSpinBox *spinBox = new QSpinBox();
            spinBox->setValue(value.toInt());
            spinBox->setRange(0, 100);
            spinBox->setSingleStep(1);
            layout->addWidget(spinBox);
            m_editWidgets[spinBox] = qMakePair(configIndex, qMakePair(itemIndex, key));
        }
        // 模式选择使用QComboBox
        else if (key == "mode") {
            QComboBox *comboBox = new QComboBox();
            comboBox->addItems({"input", "output", "analog", "pwm"});
            comboBox->setCurrentText(value.toString());
            layout->addWidget(comboBox);
            m_editWidgets[comboBox] = qMakePair(configIndex, qMakePair(itemIndex, key));
        }
        // 其他字符串使用QLineEdit
        else {
            QLineEdit *lineEdit = new QLineEdit(value.toString());
            layout->addWidget(lineEdit);
            m_editWidgets[lineEdit] = qMakePair(configIndex, qMakePair(itemIndex, key));
        }
    }
    else {
        QLabel *label = new QLabel(value.toVariant().toString());
        layout->addWidget(label);
    }

    return container;
}

QJsonValue ConfigViewManager::getValueFromWidget(QWidget *widget) const
{
    if (QCheckBox *checkBox = qobject_cast<QCheckBox*>(widget)) {
        return checkBox->isChecked();
    }
    else if (QComboBox *comboBox = qobject_cast<QComboBox*>(widget)) {
        return comboBox->currentText();
    }
    else if (QLineEdit *lineEdit = qobject_cast<QLineEdit*>(widget)) {
        return lineEdit->text();
    }
    else if (QDoubleSpinBox *spinBox = qobject_cast<QDoubleSpinBox*>(widget)) {
        return spinBox->value();
    }
    else if (QSpinBox *spinBox = qobject_cast<QSpinBox*>(widget)) {
        return spinBox->value();
    }

    return QJsonValue();
}
